// pages/index/activity/work/add_work/add_work.js
import Toast from "../../../../../miniprogram_npm/@vant/weapp/toast/toast"
import Dialog from "../../../../../miniprogram_npm/@vant/weapp/dialog/dialog"
const app = getApp()
//获取 log 日志打印
const log = new app.appLogs()
//获取 http 网络请求
const http = new app.appHttp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    theme: {},
    id: null,
    yardId: null,
    desc: "",
    fileList: [],
    successFileNumber: 0,
    upFileNumber: 0,
    upFiles: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.setNavigationBarTitle({
      title: "上传作品"
    })
    this.setData({
      theme: app.globalData.theme,
      id: options.id
    })
    this.getYardId()
  },

  /**
   * 获取院落id
   */
  getYardId: function () {
    http.get("room/default", {
      people_id: app.globalData.userInfo.people_id,
      applet_id: app.globalData.userInfo.applet_id,
    }).then(res => {
      if (res.data.code === http.REQUEST_OK) {
        this.data.yardId = res.data.data.yardId
      }
    })
  },

  /**
   * 实时获取输入描述信息
   * @param e
   */
  onInputDesc: function (e) {
    this.setData({
      desc: e.detail.value
    })
  },

  /**
   * 添加附件
   * @param e
   */
  onCameraFile: function (e) {
    wx.chooseImage({
      count: 9,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: res => {
        if (this.data.fileList.length < 9) {
          res.tempFiles.forEach(item => {
            if (this.data.fileList.length < 9) {
              this.data.fileList.push(item)
            }
          })
          this.setData({
            fileList: this.data.fileList
          })
        }
      }
    })
  },

  /**
   * 预览图片
   * @param e
   */
  onFilePreview: function (e) {
    const index = e.currentTarget.dataset.index
    wx.previewImage({
      urls: [this.data.fileList[index].path]
    })
  },

  /**
   * 删除附件
   * @param e
   */
  onFileDelete: function (e) {
    const index = e.currentTarget.dataset.index
    this.data.fileList.splice(index,1)
    this.setData({
      fileList: this.data.fileList
    })
  },

  /**
   * 删除图片
   */
  deleteImage: function (e) {
    const than = this
    const index = e.detail.index
    this.data.fileList.splice(index, 1)
    than.setData({
      fileList: than.data.fileList
    })

  },
  /**
   * 图片上传
   */
  afterRead: function (e) {
    const than = this
    for (let i = 0; i < e.detail.file.length; i++) {
      than.data.fileList.push({
        url: e.detail.file[i].path,
        name: e.detail.file[i].size
      })
    }
    than.setData({
      fileList: than.data.fileList
    })
  },

  /**
   * 上传活动作品
   * @param e
   */
  onSubmitWork: function (e) {
    if (this.data.desc == null || this.data.desc.length <= 0) {
      Toast.fail("请输入作品描述")
      return 0
    }
    if (this.data.fileList.length <= 0) {
      Toast.fail("请上传作品附件")
      return 0
    }
    Dialog.confirm({
      title: "上传作品",
      message: "确定要上传该作品吗？"
    }).then(() => {
      Dialog.close()
      log.e("提交数据")
      Toast.loading({
        duration: 0,
        message: "上传中..."
      })
      this.data.successFileNumber = 0
      this.data.upFileNumber = 0
      this.data.upFiles = []
      this.data.fileList.forEach(item => {
        http.upFile(item.url,"work").then(res => {
          if (res.code === http.REQUEST_OK) {
            this.data.successFileNumber += 1
            this.data.upFiles.push(res.data)
          }
          this.data.upFileNumber += 1
        }, err => {
          this.data.upFileNumber += 1
        })
      })
      const pd = setInterval(() => {
        log.e("当前上传成功数: " + this.data.successFileNumber)
        log.e("当前上传总数: " + this.data.upFileNumber)
        if (this.data.upFileNumber >= this.data.fileList.length) {
          clearInterval(pd)
          if (this.data.upFileNumber < this.data.fileList.length) {
            Toast.fail("附件上传失败")
            return
          }
          log.e("附件上传成功")
          let files = []
          this.data.upFiles.forEach(item => {
            files.push({
              attachment_name: item.name,
              attachment_url: item.url,
              attachment_type: 1
            })
          })
          http.postJson("activity-work/add",{
            activity_id: this.data.id,
            yard_id: this.data.yardId,
            work_desc: this.data.desc,
            work_file: files
          }).then(res => {
            if (res.data.code === http.REQUEST_OK) {
              Toast.success("上传成功")
              setTimeout(() => {
                wx.navigateBack()
              },2000)
            }else  {
              Toast.clear()
              Dialog.alert({
                title: "上传失败",
                message: res.data.msg
              }).then(() => {

              })
            }
          }, err => {
            Toast.clear()
            Dialog.alert({
              title: "上传失败",
              message: "网络异常"
            }).then(() => {

            })
          })
        }
      },1000)
    }).catch(() => {
      log.e("取消")
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})